package top.hkyzf.study.leetcode.tree;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * description: 
 * @author zhufeng
 * @date 2024/2/21 0021 9:29
 * @version V1.0
 */
public class 从中序与后序遍历序列构造二叉树_106 {
    Map<Integer, Integer> inCache = new HashMap<>();
    Map<Integer, Integer> postCache = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < postorder.length; i++) {
            postCache.put(postorder[i], i);
        }
        for (int i = 0; i < inorder.length; i++) {
            inCache.put(inorder[i], i);
        }
        TreeNode root = new TreeNode(postorder[postorder.length-1]);
        int index = inCache.get(root.val);
        root.left = getRoot(postorder, inorder, 0, index-1);
        root.right = getRoot(postorder, inorder, index+1, inorder.length-1);
        return root;
    }

    public TreeNode getRoot(int[] postorder, int[] inorder, int start, int end) {
        if (start == end) {
            return new TreeNode(inorder[start]);
        }
        if (start > end) {
            return null;
        }
        int[] ids = {-1, -1};
        for (int i = start; i <= end; i++) {
            if (ids[0] < postCache.get(inorder[i])) {
                ids[0] = postCache.get(inorder[i]);
                ids[1] = i;
            }
        }
        TreeNode root = new TreeNode(postorder[ids[0]]);
        root.left = getRoot(postorder, inorder, start, ids[1]-1);
        root.right = getRoot(postorder, inorder, ids[1]+1, end);
        return root;
    }

    @Test
    public void testBuildTree () {
        int[] inorder = {9,3,15,20,7};
        int[] postorder = {9,15,7,20,3};
        TreeNode treeNode = buildTree(inorder, postorder);
        treeNode.print();
    }
}
